<template>
  <view v-if="!withPullRefresh" class="app-layout" :class="{'h5-with-tabbar': h5.withTabbar}">
    <slot></slot>
  </view>
  <scroll-view
    v-else
    class="app-layout"
    :class="{'h5-with-tabbar': h5.withTabbar}"
    :scroll-y="true"
    :refresher-enabled="true"
    :refresher-triggered="scrollView.triggered"
    :refresher-threshold="100"
    :refresher-background="refresherBackground"
    :scroll-with-animation="true"
    @refresherpulling="handlePulling"
    @refresherrefresh="handleRefresh"
    @refresherrestore="handleRestore"
    @refresherabort="handleAbort"
  >
    <slot></slot>
  </scroll-view>
</template>

<script>
  export default {
    name: 'AppLayout',
    props: {
      // 是否需要下拉刷新
      withPullRefresh: {
        default: false
      },
      // 下拉刷新的背景色
      refresherBackground: {
        default: '#f7f7f7'
      }
    },
    data() {
      return {
        // h5相关
        h5: {
          withTabbar: false,
        },
        // scrollView相关
        scrollView: {
          triggered: true,
          _freshing: false
        }
      }
    },
    methods: {
      // 标记为刷新完成
      refreshDone() {
        this.scrollView.triggered = false;
        this.scrollView._freshing = false;
      },
      // 下拉
      handlePulling(e) {
        this.$emit('pulling', e)
      },
      // 刷新数据
      handleRefresh(e) {
        if (this.scrollView._freshing) {
          return
        }
        this.scrollView._freshing = true
        this.$emit('refresh', e)
      },
      // 重置组件
      handleRestore() {
        // 需要重置
        this.scrollView.triggered = 'restore'
      },
      // 下拉中止
      handleAbort(e) {
        this.$emit('abort', e)
      },
      /**
       * 初始化withTabbar，判断是否存在底部菜单，用于动态设置layout高度
       */
      __initWithTabbar () {
        // #ifdef H5
        const tabbar = document.querySelector('.uni-tabbar-bottom')
        if (tabbar == null) {
          this.h5.withTabbar = false
          return
        }
        if (tabbar.style.display === 'none') {
          this.h5.withTabbar = false
          return
        }
        this.h5.withTabbar = true
        // #endif
      }
    },
    mounted () {
      this.__initWithTabbar()
    }
  }
</script>

<style scoped lang="scss">
  @import "../style/variables";

  .app-layout {
    position: fixed;
    left: 0;
    right: 0;
    /* #ifdef H5 */
    top: 44px;
    /* #endif */
    /* #ifndef H5 */
    top: 0;
    /* #endif */
    bottom: 0;
    background-color: $background-color;
    font-size: $font-size;
    font-family: $font-family;
    color: $font-color;
    overflow-y: auto;
    // h5包含tabbar
    &.h5-with-tabbar {
      bottom: 50px;
    }
  }
</style>
